import { $storage, $event } from '../utils'
import { GlobalData } from './state'

/** 获取当前服务器 */
export function getServer(): DomoServer {
  return GlobalData.server
}

/** 判断用户是否登录 */
export function isLogin(): boolean {
  const token = wx.getStorageSync(`${getServer()}/accessToken`).data
  return !!token
}

/** 设置当前服务器 */
export function setServer(server: DomoServer) {
  GlobalData.server = server
}

export function setCurrencyName(currencyName: string) {
  GlobalData.currencyName = currencyName
}

/**
 * 存储用户认证信息 AccessToken
 * @param token
 * @param expireIn 单位: 分钟
 */
export function setAccessToken(token: string, expireIn: number) {
  $storage.set('accessToken', token, {
    expires: expireIn,
  })
}

/** 读取 AccessToken */
export function getAccessToken() {
  return $storage.get('accessToken')
}

/** 根据数组某一字段进行排序 */
export function arraysort(name: any) {
  return (a: any, b: any) => {
    return b[name] - a[name]
  }
}

/** 获取广告 */

export function getAdvertising(name: string, advertisingList: any[], advertisingspace: any[]) {
  const list = advertisingList.filter(
    (item: { space_id: any }) =>
      item.space_id === advertisingspace.find((item: { space: string }) => item.space === name).id,
  )
  return list.sort(arraysort('sort'))
}

export function vipTime(utcDate: Date) {
  //获取本地时间与格林威治时间的时间差(注意是分钟，记得转换)
  const diff = new Date().getTimezoneOffset() * 60 * 1000
  const date = new Date(utcDate.getTime() - diff)
  //根据格林威治时间和各地时区，得到各地时区的时间
  const now = new Date()
  if (now.getFullYear() === date.getFullYear()) {
    if (date.getMonth() === now.getMonth()) {
      if (date.getDate() === now.getDate()) {
        return '今天'
      } else if (date.getDate() === now.getDate() + 1) {
        return '明天'
      } else if (date.getDate() === now.getDate() + 2) {
        return '后天'
      } else {
        return `本月${date.getDate()}日` //  ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}
      }
    } else {
      return `${date.getMonth() + 1}-${date.getDate()}` // ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}
    }
  } else {
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}` // ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}
  }
}

/**
 * 检查用户是否是VIP， 以及是否已经过期了
 *  return  true 当前还是vip
 */
export function checkUserisVip(user: DomoUser) {
  if (user && user.vip) {
    const time = new Date(user.vip.end_time)
    // const diff = new Date().getTimezoneOffset() // 零时区时间差单位为分钟
    // console.log('-------', time.getTime() - new Date().getTime())
    return time.getTime() - new Date().getTime() > 1
  } else {
    return false
  }
}

/** 格式化时间
 * @param date 时间对象
 * @param format 格式化,不传默认输出'YYYY-MM-DD hh:mm:ss'
 * @example
 *formatDateTime(data,format)
 */
export function formatDateTime(date: Date, format = 'YYYY-MM-DD') {
  let hour = date.getHours()
  let minute = date.getMinutes()
  let second = date.getSeconds()
  const year = date.getFullYear()
  let month = date.getMonth()
  let day = date.getDate()
  if (hour < 10) {
    hour = 0 + hour
  }
  if (minute < 10) {
    minute = 0 + minute
  }
  if (second < 10) {
    second = 0 + second
  }
  month = month + 1
  if (month < 10) {
    month = 0 + month
  }
  if (day < 10) {
    day = 0 + day
  }
  const time =
    format === 'YYYY-MM-DD'
      ? `${year}-${month}-${day}`
      : format === 'YYYYMMDDhhmmss'
        ? `${year}${month}${day}${hour}${minute}${second}`
        : format === 'YYYY-MM-DD hh:mm'
          ? `${year}-${month}-${day} ${hour}:${minute}`
          : `${year}-${month}-${day} ${hour}:${minute}:${second}`
  return time
}

/** 订阅消息 */
export function onNews(id = [] as string[]) {
  return new Promise((resolve, reject) => {
    wx.requestSubscribeMessage({
      tmplIds: id,
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}

/** 获取当前小程序的APPid */
export function getAppId() {
  const accountInfo = wx.getAccountInfoSync()
  return accountInfo.miniProgram.appId
}

/** 401状态码触发登录 */
export function loginagin() {
  return $event.emit('login')
}

/** 禁用用户 */
export function blacklistUser() {
  wx.showModal({
    title: '提示',
    content: '用户暂时不能登录,请联系管理员',
    success(res) {
      if (res.confirm) {
        wx.switchTab({
          url: '/pages/feed/list/list',
        })
      } else if (res.cancel) {
        wx.switchTab({
          url: '/pages/feed/list/list',
        })
      }
    },
  })
  // WechatMiniprogram.showToast({
  //   title: '用户暂时不能登录,请联系管理员',
  //   icon: 'none',
  // })
  // setTimeout(() => {
  //   WechatMiniprogram.switchTab({
  //     url: '/pages/feed/list/list',
  //   })
  // }, 1000)
}
